
import json
import time
import pymysql
import yaml
import sys
import os
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)


class Tools:

    # 读取yaml文件，返回python对象
    def yaml_load(self, file_path):

        if 'yml' in file_path or 'yaml' in file_path:
            with open(file=file_path, mode='r', encoding='utf8')as f:
                return yaml.safe_load(f)
        else:
            raise Exception('需要传入yaml格式的文件')

    def get_rootdir(self):

        curPath = os.path.abspath(os.path.dirname(__file__))
        rootPath = os.path.split(curPath)[0]
        return rootPath

    def replace(self, filename, data: dict):
        """
        参数替换
        :param filename: 需替换的yaml文件
        :param data: 需替换的参数
        :return: 原本yaml文件替换过后所对应的python object
        """
        with open(filename, 'r', encoding='utf-8-sig', errors='ignore')as f:
            str1 = str(yaml.safe_load(f))
            # str1 = f.read()
            for key, value in data.items():
                need_replace = '$' + key
                str1 = str1.replace(need_replace, str(value), 999)
                str2 = str1.replace('\'', '\"', 99999)
            return json.loads(str2, encoding='utf-8-sig')

    # 执行数据库操作,需要在内网环境操作
    def db(self, sql: str, database=None):
        """
        数据库操作
        :param sql:需执行的sql语句
        :return: 执行后的结果，为元组类型
        """

        db_conf = yaml.safe_load(
            open(self.get_rootdir() + '/conf/database.yml'))
        if database not in db_conf.keys():
            print('数据库配置文件中没有包含%s的数据库,使用默认数据库' % database)
            db_env = db_conf[db_conf['default']]
        else:
            db_env = db_conf[database]
        db = pymysql.Connect(**db_env)
        cursor = db.cursor()
        try:
            cursor.execute(sql)
            db.commit()

        except Exception as e:
            raise Exception(e)
        else:
            try:
                # data1=cursor.fetchone()#返回第一行
                data2 = cursor.fetchall()  # 返回所有结果
                return data2
            except Exception as e1:
                raise Exception(e1)
        finally:
            cursor.close()

    def get_new_token_from_db(self, code):
        sql = 'select auth_key from user where moego_code = {}'.format(code)
        token = self.db(sql)[0][0]
        return token

    def set_new_token_to_global(self, code):
        token = self.get_new_token_from_db(code)
        self.set_global({'token': token})
        return token

    def get_new_token_from_login(self, accountName):
        from api.baseapi import BaseApi
        obj = BaseApi()
        accounts = yaml.safe_load(
            open(self.get_rootdir() + '/conf/account.yml'))
        if accountName not in accounts.keys():
            print('账号配置文件中没有包含%s的账号' % accountName)
            account = accounts[accounts['default']]
        else:
            account = accounts[accountName]
        login_data = {'method': 'post', "url": "/admin-api/system/auth/sms-login-password",
                      'json': account}
        data = obj.send(login_data)
        print(data.json())
        token = data.json()['data']['accessToken']
        self.set_global({'token': token})
        return token

    def get_timestamp(self):
        return int(time.time())

    def get_env(self):
        envs = yaml.safe_load(open(self.get_rootdir() + '/conf/env.yml'))
        return envs['env'][envs['default']]

    def set_global(self, data: dict):
        global_params = yaml.safe_load(
            open(self.get_rootdir() + '/conf/global.yml'))
        print(global_params)
        param_names = global_params.keys()
        for key in data.keys():
            if key not in param_names:
                print('变量中没有包含%s的变量名' % key)
        for key, value in data.items():
            global_params[key] = value
            print('设置变量   ' + key + '：' + value)
        # print(global_params)
        with open(self.get_rootdir() + '/conf/global.yml', 'w', encoding='utf8') as f:
            yaml.safe_dump(global_params, f)

    def get_global(self, params_name: str):
        global_params = yaml.safe_load(
            open(self.get_rootdir() + '/conf/global.yml'))
        if params_name not in global_params.keys():
            raise Exception('变量中没有包含%s的变量名' % params_name)
        else:
            return global_params[params_name]

    def json_loads(self, json_str):
        """

        :param json_str: json字符串
        :return: 字典
        """
        try:
            return json.loads(json_str)
        except BaseException as e:
            print('{}不是json字符串'.format(json_str) + str(e))


if __name__ == '__main__':
    # a = Tools().db("SELECT * FROM `ruoyi-vue-pro`.`system_users` WHERE `mobile` LIKE '%0021%' LIMIT 0,1")
    # print(a[0])
    t = Tools().get_new_token_from_login('account1')
    print(t)
